package com.demo.rabbit.client.mandatory;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * 简单队列消费者
 */
public class ProducerBatchConfirmConsumer {

	public static void main(String[] args) throws Exception {
		// 1、创建连接工厂
		ConnectionFactory factory = new ConnectionFactory();
		// 2、设置连接属性
		factory.setHost("localhost");
		factory.setUsername("admin");
		factory.setPassword("admin");

		try (
				// 3、从连接工厂获取连接
				Connection connection = factory.newConnection("消费者");
				// 4、从链接中创建通道
				Channel channel = connection.createChannel();) {
			String queueName = channel.queueDeclare().getQueue();
			channel.exchangeDeclare("mandatory-ex", "fanout");
			channel.queueBind(queueName, "mandatory-ex", "");
			// 6、定义收到消息后的回调
			DeliverCallback callback = new DeliverCallback() {
				public void handle(String consumerTag, Delivery message) throws IOException {
					System.out.println("收到消息：" + new String(message.getBody(), "UTF-8"));
				}
			};

			// 7、开启队列消费
			String consumerTag = channel.basicConsume(queueName, true, callback, new CancelCallback() {
				public void handle(String consumerTag) throws IOException {
				}
			});

			System.out.println("开始接收消息");
			System.in.read();

		}
	}
}
